(function(app){
	var lastAndCallback = "&callback=JSON_CALLBACK";
	app
	
	.factory("loginFac",["$http",function($http){
		var factory = {};
		var baseUrl = SERVER_IP+"handler/Login.ashx";
		factory.UserLogin = function(loginname,loginpwd,domaincheck,domainname,extparam){
			loginname = escape(loginname);
			loginpwd = escape(loginpwd);
			domaincheck = escape(domaincheck);
			domainname = escape(domainname);
			extparam = escape(extparam);
			var parms = "operateType=userLogin"+
						"&loginName="+loginname+
						"&loginPwd="+loginpwd+
						"&domainCheck="+domaincheck+
						"&domainName="+domainname+
						"&extParam="+extparam;
			var jsonpUrl = baseUrl+"?"+parms;
			
			return $http.jsonp(jsonpUrl);
		};
		factory.UpdatePwd = function(userId,oldPwd,newPwd,hostName){
			userId = escape(userId);
			oldPwd = escape(oldPwd);
			newPwd = escape(newPwd);
			hostName = escape(hostName);
			var parms = "userid="+userId+"&oldPwd="+oldPwd+"&newPwd="+newPwd+"&hostName="+hostName;
			var jsonpUrl = baseUrl+"UpdatePwd?"+parms+"&callback=JSON_CALLBACK";
			return $http.jsonp(jsonpUrl)
		};
		factory.LoginOut = function(userName,IP,hostName){
			userName = escape(userName);
			IP = escape(IP);
			hostName = escape(hostName);
			var parms = "userName="+userName+"&IP="+IP+"&hostName="+hostName;
			var jsonpUrl = baseUrl+"LoginOut?"+parms+lastAndCallback;
			return $http.jsonp(jsonpUrl)
		};
		return factory;
	}])

	.factory("fileFac",["$http",function($http){
		var factory = {};
		var baseUrl = SERVER_IP+"file/";
		return factory;
	}])
	
	
	.factory('Alert', ['$timeout','$ionicPopup', function($timeout,$ionicPopup) {
		  return {
		    plmAlert : function(alertMsg,dayLay){
				var myPopup = $ionicPopup.show({title: alertMsg});
	           	$timeout(function(){myPopup.close();},dayLay);
		    }
		  };
	}])
	//angularjs封装$http为factory      https://www.cnblogs.com/xfdmb/p/6539434.html
	.factory('HttpGet', function ($http, $state,$timeout,$ionicLoading, $q, Alert){  
    	var factory = {};  
    	factory.get = function(endpoint) {  
	        var defer = $q.defer();
			$http.get(endpoint, { timeout: 10000 }).success(function (data) {
				$ionicLoading.hide();
				if(data.success == "sessiontimeout"){
					Alert.plmAlert("网络超时",1000);
					$timeout(function(){$state.go("login",{},{reload:true});},1000);
					defer.reject();
				}else if(data.success == "-9999"){
					Alert.plmAlert(data.message,1000);
					$timeout(function(){$state.go("login",{},{reload:true});},1000);
					defer.reject();
				} else {
					defer.resolve(data);  
				}
			}).error(function (data) {
				$ionicLoading.hide();
				Alert.plmAlert("获取失败",1000);
				defer.reject();
			});
	        	return defer.promise;  
        };
        
        	factory.get2 = function(endpoint) {  
			var defer = $q.defer();
			$http.get(endpoint, { timeout: 10000 }).success(function (data) {
				$ionicLoading.hide();
				if(data.success == "sessiontimeout"){
					$timeout(function(){$state.go("login",{},{reload:true});},1000);
					defer.reject("网络超时");
				}else if(data.success == "-9999"){
					$timeout(function(){$state.go("login",{},{reload:true});},1000);
					defer.reject(data.message);
				} else {
					defer.resolve(data);
				}
			}).error(function (data) {
				$ionicLoading.hide();
				defer.reject("获取失败");
			});
			return defer.promise;
	    	};
	    	
	    	factory.post = function(endpoint,params) {  
			var defer = $q.defer();
			
			
			$.ajax({
				type:"POST",
				url:endpoint,
				data:params,
		        dataType: "json",
		        timeout: 10000,
				async:true,
				success: function(data){
					$ionicLoading.hide();
					if(data.success == "sessiontimeout"){
						$timeout(function(){$state.go("login",{},{reload:true});},1000);
						defer.reject("网络超时");
					}else if(data.success == "-9999"){
						$timeout(function(){$state.go("login",{},{reload:true});},1000);
						defer.reject(data.message);
					} else {
						defer.resolve(data);
					}
				},
				error:function (xhr, textStatus, errorThrown) {
					$ionicLoading.hide();
					defer.reject("获取失败");
　　　　			} 
			});
			
			return defer.promise;
			
			
			
//			$http({  
//              url: endpoint,  
//              method: 'POST',  
//              headers: { timeout: 10000,'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',},  
//              data: $.param(params),
//          }).success(function (data) {  
//              $ionicLoading.hide();
//				if(data.success == "sessiontimeout"){
//					$timeout(function(){$state.go("login",{},{reload:true});},1000);
//					defer.reject("网络超时");
//				}else if(data.success == "-9999"){
//					$timeout(function(){$state.go("login",{},{reload:true});},1000);
//					defer.reject(data.message);
//				} else {
//					defer.resolve(data);
//				}
//          }).  
//          error(function (data, status, headers, config) {  
//              $ionicLoading.hide();
//				defer.reject("获取失败");
//          });  
//			return defer.promise;
	    	};
        
        
        var newtime = 0;
        factory.MultipleSubmit = function() {  
        	  var Today = new Date();
			  var Hour = Today.getHours();
			  var Minute = Today.getMinutes();
			  var Second = Today.getSeconds();
			  var nowtime = (Hour*3600) + (Minute*60) + Second;
			  if((nowtime-newtime)>2){
			    newtime = nowtime;
			    return false;
			  }else{
			    return true;
			  }
        };
        
        return factory;  
	})
	.factory('Userinfo', function () {
        var userinfo = {};

        return {
            save: function (j) {
                for (var k in j) {
                    window.localStorage[k] = userinfo[k] = j[k];
                }

                return userinfo;
            },

            remove: function (f) {
                if (f.constructor == Array) {
                    for (var i = 0; i < f.length; i++) {
                        window.localStorage.removeItem(f[i]);
                    }
                }
                window.localStorage.removeItem(f);
            },

            add: function (k, v) {
                try {
    				window.localStorage[k] = userinfo[k] = v;
				} catch(e) {
				    alert("本地储存写入错误，若为safari浏览器请关闭无痕模式浏览。");
				}
            },
            get: function (k) {
                return window.localStorage[k];
            },

            addLong: function (k, v) {
                window.localStorage[k] = v;
            },

            l: window.localStorage
        };
    })
	.factory('Array', function () {

        var Array = [];

        return {
            save: function (j) {
                for (var k = 0; k < j.length; k++) {
                    Array.push(j[k]);
                }
            },
            remove: function (one) {
                Array.splice(Array.indexOf(one), 1);
            },
            removeAll: function () {
                Array.splice(0,Array.length);
            },
            add: function (one) {
                Array.push(one);
            },
            get: function (title) {
                for (var i = 0; i < Array.length; i++) {
                    if (Array[i].title === title) {
                        return Array[i];
                    }
                }
                return null;
            },
            get_obj: function (obj) {
                for (var i = 0; i < Array.length; i++) {
                    if (angular.lowercase(Array[i].DRAWINGNO) == angular.lowercase(obj.DRAWINGNO)) {
                        return Array[i];
                    }
                }
                return null;
            },
            //修改时候，数组里排除当前图号
            get_obj_except: function (obj,except) {
                for (var i = 0; i < Array.length; i++) {
                    if (angular.lowercase(Array[i].DRAWINGNO) == angular.lowercase(obj.DRAWINGNO)) {
                    	if(angular.lowercase(Array[i].DRAWINGNO) != angular.lowercase(except.DRAWINGNO)){
                    		return Array[i];
                    	}
                    }
                }
                return null;
            },
            all: Array
        }
    })
	
	
})(app)
